import os
from util.md5 import getmd5, getcrc
import json

from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from django.http import FileResponse

from util.exception import ValidationError
from util.anaFile import AnaFile
from util.jsonDeal import JsonDeal
from django.conf import settings


class DownLoadViewset(GenericViewSet):
    @action(detail=False, methods=["GET", ], url_path="down")
    def dir_path(self, requests, *args, **kwargs):
        file_path = requests.GET.get("file_path")
        file_paths = file_path.split("/")
        file_name = file_paths[-1]
        if os.path.exists(file_path):
            if os.path.isfile(file_path):
                try:
                    file = open(file_path, 'rb')
                    response = FileResponse(file)
                    response['Content-Type'] = 'application/octet-stream'
                    response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)
                    return response
                except:
                    raise ValidationError(70002)
        else:
            raise ValidationError(50004)

    @action(detail=False, methods=["POST", ], url_path="json")
    def json_config_files_write(self, requests, *args, **kwargs):
        myFile = requests.FILES.get("file")
        if not myFile:
            raise ValidationError(50002)
        name = settings.JSON_EXPLAIN_FILE
        try:
            dir_name = settings.JSON_CONFIG_FILE_PATH
            os.makedirs(dir_name, exist_ok=True)
            file_path = "".join([dir_name, "/", name])
            destination = open(os.path.join(file_path), "wb+")
            for chunk in myFile.chunks():
                destination.write(chunk)
            destination.close()
            return Response({
                "code": 200,
                "msg": "上传成功"
            })
        except Exception as e:
            raise ValidationError(70001)

    @action(detail=False, methods=["POST", ], url_path="upload")
    def files_write(self, requests, *args, **kwargs):
        file_path = requests.GET.get("file_path")
        myFile = requests.FILES.get("file")
        if not myFile:
            raise ValidationError(50002)
        name = myFile.name
        try:
            file_paths = file_path.split("/")
            file_name = file_paths[-1]
            dir_name = "/".join(file_paths[:-1])
            os.makedirs(dir_name, exist_ok=True)
            destination = open(os.path.join(file_path), "wb+")
            for chunk in myFile.chunks():
                destination.write(chunk)
            destination.close()
            return Response({
                "code": 200,
                "msg": "上传成功"
            })
        except Exception as e:
            raise ValidationError(70001)

    @action(detail=False, methods=["POST", ], url_path="exupload")
    def ex_files_write(self, requests, *args, **kwargs):
        file_path = requests.GET.get("file_path")
        myFile = requests.FILES.get("file")
        if not myFile:
            raise ValidationError(50002)
        name = myFile.name
        try:
            file_paths = file_path.split("/")
            dir_name = "/".join(file_paths)
            os.makedirs(dir_name, exist_ok=True)
            file_paths.append(name)
            file_path = "/".join(file_paths)
            destination = open(os.path.join(file_path), "wb+")
            for chunk in myFile.chunks():
                destination.write(chunk)
            destination.close()
            return Response({
                "code": 200,
                "msg": "上传成功"
            })
        except Exception as e:
            print(e)
            return Response({
                "code": 200,
                "msg": str(e)
            })

    @action(detail=False, methods=["GET", ], url_path="is_file")
    def is_file(self, requests, *args, **kwargs):
        file_path = requests.GET.get("file_path")
        md5 = requests.GET.get("md5")
        if os.path.isfile(file_path):
            return Response({
                "is_file": 1
            })
        else:
            return Response({
                "is_file": 0
            })

    @action(detail=False, methods=["GET", ], url_path="get_md5")
    def get_md5(self, requests, *args, **kwargs):
        file_path = requests.GET.get("file_path")
        is_new = requests.GET.get("is_new")
        if os.path.isfile(file_path):
            if is_new == "0":
                md5 = getmd5(file_path)
            else:
                md5 = getcrc(file_path, False)
            return Response({
                "md5": md5
            })
        else:
            return Response({
                "md5": ""
            })

    @action(detail=False, methods=["GET", ], url_path="remove_file")
    def remove_file(self, requests, *args, **kwargs):
        file_path = requests.GET.get("file_path")
        if os.path.exists(file_path):
            os.remove(file_path)
        return Response({})

    @action(detail=False, methods=["GET", ], url_path="ana_file")
    def ana_file(self, requests, *args, **kwargs):
        file_path = requests.GET.get("file_path")
        if os.path.isfile(file_path):
            file_name = file_path.split("/")[-1]
            explain_file_path = "".join([settings.DEPLOY_FILE_DIR, "/", file_name])
            content = JsonDeal.get_new_json(file_path)
            explian_data = JsonDeal.get_qianduan(explain_file_path, content)
            ana_file = AnaFile(explian_data.get("data"))
            results = ana_file.ana_file()
            return Response({
                "sensor_ids": results
            })
        else:
            return Response({
                "sensor_ids": []
            })
